package com.yuba.common.ai.config;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.ai.autoconfigure.vectorstore.redis.RedisVectorStoreProperties;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.RedisVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPooled;

/**
 * Redis向量存储配置
 */

// 读取RedisStack的配置信息
@EnableConfigurationProperties({RedisVectorStoreProperties.class})
@Configuration
@Setter
@Getter
public class RedisVectorConfig {

    @Value("${spring.ai.vectorstore.redis.host}")
    private String redisVectorHost;
    @Value("${spring.ai.vectorstore.redis.port}")
    private int redisVectorPort;
    @Value("${spring.ai.vectorstore.redis.username}")
    private String redisVectorUsername;
    @Value("${spring.ai.vectorstore.redis.password}")
    private String redisVectorPassword;

    /**
     * 创建RedisStack向量数据库
     *
     * @param embeddingModel 嵌入模型
     * @param properties     redis-stack的配置信息
     * @return vectorStore 向量数据库
     */
    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel,
                                   RedisVectorStoreProperties properties
                                   /*RedisConnectionDetails redisConnectionDetails*/) {
        RedisVectorStore.RedisVectorStoreConfig config = RedisVectorStore.RedisVectorStoreConfig.builder().withIndexName(properties.getIndex()).withPrefix(properties.getPrefix()).build();
        // 创建连接池配置
        GenericObjectPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxIdle(8);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(3000);
        // 创建 Jedis 连接
        JedisPooled jedisPooled = new JedisPooled(
            poolConfig,
            redisVectorHost,  // host
            redisVectorPort,  // port
            10000,  // connectionTimeout
           redisVectorUsername,
           redisVectorPassword,
           false
        );
        return new RedisVectorStore(config, embeddingModel,
            jedisPooled,
                properties.isInitializeSchema());
    }
}
